import signal

from flask import Flask

from init.message_load import load_all_messages
from utils.restrict_tool.restrict_tool import RestrictTool
from utils.token import TokenHandler


# from extensions.celery_extensions import celery_init_app


def set_blueprint(app: Flask):
    from apps.user import user_blueprint
    from apps.goods import goods_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/api/v1/user')
    app.register_blueprint(goods_blueprint, url_prefix='/api/v1/goods')


def set_db(app: Flask):
    from utils.log import log_api
    from sqlalchemy import create_engine
    from config import server_config
    from database.db_manager import init_session

    log_api.info(f'load database connection config.')
    app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URL']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_POOL_SIZE'] = 20
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = 40
    echo_sql = app.config.get('ECHO_SQL', False)
    server_config.db_engine = create_engine(app.config['DATABASE_URL'], echo=echo_sql)
    init_session()


def set_redis():
    from config import server_config
    from utils.redis_helper import RedisUtil
    server_config.redis_util = RedisUtil(server_config.redis_host, server_config.redis_port)
    redis_client = server_config.redis_util.get_redis_client()
    redis_client.ping()
    redis_client.close()

    from utils import redis_helper
    redis_helper.redis_util = RedisUtil(server_config.redis_host, server_config.redis_port)
    # check redis server could to connect
    redis_client = redis_helper.redis_util.get_redis_client()
    redis_client.ping()
    redis_client.close()


def set_utils():
    from config import server_config
    server_config.token_util = TokenHandler(run_mode=server_config.run_mode)

    server_config.restrict_tool = RestrictTool()


def server_shutdown(args, kwargs):
    from utils.log import log_api
    log_api.info(f'server shutdown. args={args} kwargs={kwargs}')
    exit(0)


def load_env_config(app: Flask):
    from utils.log import log_api
    from config import server_config
    log_api.info(f'load server env config.')

    server_config.web_addr = app.config['WEB_SERVER_ADDR']
    server_config.web_port = app.config['WEB_SERVER_PORT']
    server_config.log_path = app.config['LOG_PATH']
    server_config.run_mode = app.config['RUN_MODE']
    server_config.redis_host = app.config['REDIS_HOST']
    server_config.redis_port = app.config['REDIS_PORT']

    signal.signal(signal.SIGINT, server_shutdown)


def load_config(app: Flask):
    load_env_config(app)
    set_db(app)
    # set_redis()
    set_utils()
    set_blueprint(app)
    load_all_messages()
    # celery_init_app(app)
